package com.qf.day4.huihua2;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @date 2022/3/28
 * @desc
 */
@WebServlet("/session1")
public class Session1Servlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");

        String productId = req.getParameter("productId");

        if(productId.equals("1")){
            String message = "你购买的是apple笔记本";

            //获取session
            HttpSession session = req.getSession();

            //HttpSession session1 = req.getSession(false);  // 当前没有session 返回null
            //HttpSession session1 = req.getSession(true);  // 当前没有session 九创间隔新的

            // 把数据存储到 session 域对象
            session.setAttribute("message",message);

            // session 是 基于cookie 的 ，为了让关闭浏览器之后 还能找到上次的session
            // 就把session id 记录下来 ，设置有效时长
            String jsessionid = session.getId();

            Cookie cookie = new Cookie("JSESSIONID", jsessionid);
            cookie.setMaxAge(60*30);

            resp.addCookie(cookie);

            req.getRequestDispatcher("/day4/huihua2/shopCar.jsp").forward(req,resp);
        }else{
            String message = "你购买的是联想笔记本";

            //获取session
            HttpSession session = req.getSession();

            session.setAttribute("message",message);

            req.getRequestDispatcher("/day4/huihua2/shopCar.jsp").forward(req,resp);

        }

    }
}
